package com.unicom.projt.util;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;

import java.io.File;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: Lee
 * Date: 12-2-27
 * Time: 上午10:11
 */
public class HttpClientDownloadUtils {

    public interface Executor {
        void execute();
    }

    private static final int TIME_OUT = 10;

    public static void downloadFile(String url, String savePathAndName, Executor executor) throws Exception {
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        HttpConnectionParams.setConnectionTimeout(httpGet.getParams(), TIME_OUT * 1000);
        HttpResponse response = httpClient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
            FileUtils.writeByteArrayToFile(new File(savePathAndName), IOUtils.toByteArray(response.getEntity().getContent()));
        }
        executor.execute();
        httpClient.getConnectionManager().shutdown();
    }
}
